package com.liaowei.user.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liaowei.common.BaseResponse;
import com.liaowei.common.Constants;
import com.liaowei.common.ErrorCode;
import com.liaowei.exception.CustomerException;
import com.liaowei.model.domain.Article;
import com.liaowei.model.domain.UserArticleHistory;
import com.liaowei.model.param.ArticleHistoryParam;
import com.liaowei.user.mapper.UserArticleHistoryMapper;
import com.liaowei.user.model.param.PageArticleHistoryParam;
import com.liaowei.user.openfeign.ArticleClient;
import com.liaowei.user.service.UserArticleHistoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
* @author LindaMan
* @description 针对表【wy_user_article_history(用户浏览文章历史表)】的数据库操作Service实现
* @createDate 2023-05-01 17:19:40
*/
@Service
@RequiredArgsConstructor
public class UserArticleHistoryServiceImpl extends ServiceImpl<UserArticleHistoryMapper, UserArticleHistory>
    implements UserArticleHistoryService{

    private final UserArticleHistoryMapper userArticleHistoryMapper;
    private final ArticleClient articleClient;

    // 校验用户是否认证
    public void matchUser(Long userId,Long loginId){
        if (!loginId.equals(userId)){
            throw new CustomerException(Constants.PARAM_ERROR,"请先认证");
        }
    }


    /**
     * 根据userId删除全部的文章历史记录
     * @param userId 用户id
     * @return 提示信息
     */
    @Transactional
    @Override
    public String removeAllArticleHistoryByUserId(long userId) {
        long loginId = StpUtil.getLoginIdAsLong();
        // 检查用户是否合法
        matchUser(userId,loginId);

        // 删除历史记录
        try {
            LambdaQueryWrapper<UserArticleHistory> wrapper = Wrappers.lambdaQuery(UserArticleHistory.class)
                    .eq(UserArticleHistory::getUserId, userId);
            userArticleHistoryMapper.delete(wrapper);
        } catch (Exception e) {
            throw new CustomerException(ErrorCode.SYSTEM_ERROR);
        }

        return "删除成功";
    }

    /**
     * 分页查询自己的文章历史记录
     * @param historyParam 文章历史参数
     * @return List<Article> 文章列表
     */
    @Override
    public List<Article> searchArticleHistoryPage(PageArticleHistoryParam historyParam) {
        Long userId = historyParam.getUserId(); // 获取用户id
        Long loginId =  Long.parseLong(StpUtil.getLoginId().toString()); // 获取当前认证的id
        // 检查是否认证
        matchUser(userId,loginId);

        // 分页参数预处理
        int pageNum = historyParam.getPageParam().getPageNum();
        int pageSize = historyParam.getPageParam().getPageSize();
        pageNum = (pageNum - 1) * pageSize;

        // 根据用户id分页查询浏览的文章id列表
        List<Long> articleIdList = userArticleHistoryMapper.selectArticleIdsByUserId(userId,pageNum,pageSize);

        // 根据文章id列表分页查询文章列表
        List<Article> result = new ArrayList<>();
        if (articleIdList.size() > 0){
            BaseResponse<List<Article>> response = articleClient.pageByIds(articleIdList);
            if (response.getCode() != 1){
                throw new CustomerException(ErrorCode.SYSTEM_ERROR);
            }else {
                result = response.getData();
            }
        }

         return result;
    }

    /**
     * 根据用户id和文章id删除文章记录
     * @param userId 用户id
     * @param articleId 文章id
     * @return 提示信息
     */
    @Transactional
    @Override
    public String removeArticleHistoryByUserIdAndArticleId(Long userId, Long articleId) {
        // 获取当前认证的id
        Long loginId =  Long.parseLong(StpUtil.getLoginId().toString());

        // 检查当前用户是否是合法用户
        matchUser(userId,loginId);

        // 删除记录
        LambdaUpdateWrapper<UserArticleHistory> wrapper = Wrappers.lambdaUpdate(UserArticleHistory.class)
                .eq(UserArticleHistory::getUserId, userId)
                .eq(UserArticleHistory::getArticleId, articleId);
        try {
            userArticleHistoryMapper.delete(wrapper);
        }catch (Exception e){
            throw new CustomerException(ErrorCode.SYSTEM_ERROR);
        }

        return "删除成功";
    }

    /**
     * 新增文章历史记录
     * @param postHistoryParam 保存文章历史记录参数
     * @return 提示信息
     */
    @Transactional
    @Override
    public String addArticleHistory(ArticleHistoryParam postHistoryParam) {
        // 获取当前认证的id
        Long loginId =  Long.parseLong(StpUtil.getLoginId().toString());
        // 获取当前用户id
        Long userId = postHistoryParam.getUserId();
        Long articleId = postHistoryParam.getArticleId();

        // 检查当前用户是否是合法用户
        matchUser(userId,loginId);

        // 检查帖子是否存在
        BaseResponse<Article> response = articleClient.articleById(articleId);
        if (response.getCode() != 1){
            throw new CustomerException(Constants.PARAM_ERROR,"文章不存在");
        }

        // 新增历史记录
        UserArticleHistory history = new UserArticleHistory();
        history.setUserId(userId);
        history.setArticleId(articleId);
        try {
            userArticleHistoryMapper.insert(history);
        } catch (Exception e) {
            throw new CustomerException(ErrorCode.SYSTEM_ERROR);
        }

        return "新增成功";
    }
}




